<?php
if (! defined('IN_WEB')) {
    exit('Access Denied');
}

class ProductAction {

    protected $productModel;

    function __construct () {
        $this->productModel = new DbKooltaoModel('kooltao_product');
        $this->termModel = new DbKooltaoModel('kooltao_term');
        $this->userModel = new DbKooltaoModel('kooltao_user');
        $this->term_dataModel = new DbKooltaoModel('kooltao_term_data');
        $this->imageModel = new DbKooltaoModel('kooltao_images');
        $this->favoriteModel = new DbKooltaoModel('kooltao_favorite');
    }

    function productTermList ($pid) {
        $sql = "SELECT v.vid, t.tid, v.name AS vname, t.name AS tname, v.machine_name, t.parent FROM kooltao_term_data td 
		INNER JOIN kooltao_term t ON td.tid = t.tid
		INNER JOIN kooltao_vocabulary v ON t.vid = v.vid
		WHERE td.pid = $pid";
        
        $this->termModel->query($sql);
        $terms = array();
        $ptype_children = array();
        while ($row = $this->termModel->fetch_array()) {
            switch ($row['machine_name']) {
                case TERM_MACHINE_NAME_SOURCE:
                    $terms[TERM_MACHINE_NAME_SOURCE] = $row;
                    break;
                case TERM_MACHINE_NAME_PTYPE:
                    $row['parent'] == 0 &&
                     $terms[TERM_MACHINE_NAME_PTYPE_FIRST] = $row;
                    $row['parent'] > 0 &&
                     $ptype_children[] = $row;
                    break;
                case TERM_MACHINE_NAME_COLOR:
                    $terms[TERM_MACHINE_NAME_COLOR] = $row;
                    break;
            }
        }
        
        list($ptype_second, $ptype_third) = $ptype_children;
        if($ptype_third['tid'] == $ptype_second['parent']){
            $tmp = $ptype_second;
            $ptype_second = $ptype_third;
            $ptype_third = $tmp;
        }
        $terms[TERM_MACHINE_NAME_PTYPE_SECOND] = $ptype_second;
        $terms[TERM_MACHINE_NAME_PTYPE_THIRD] = $ptype_third;
        
        return $terms;
    }

    function productImgList ($pid) {
        $list = $this->imageModel->getList('*', "pid = $pid");
        $imgs = array();
        foreach ($list as $item) {
            $imgs[$item['type']] = $item;
        }
        return $imgs;
    }

    function productGetFull ($pid) {
        $product = $this->productModel->getOneById($pid);
        $product && $product['terms'] = $this->productTermList($product['pid']);
        $product && $product['images'] = $this->productImgList($product['pid']);
        
        return $product;
    }

    //一定要传入$conditions['tids']
    function productListByTids ($conditions = null) {
        $page = $conditions['page']? $conditions['page']: 0;
        $count = $conditions['count']? $conditions['count']: DEFAULT_PRODUCT_COUNT;
        $from = $page*$count;
        $sortBy = $conditions['sort'] ? $conditions['sort'] : ' p.pid DESC ';
        
        if (is_array($conditions['tids'])) {
            $conditions['tids'] = implode(', ', $conditions['tids']);
        }
        $where_str = " WHERE t.tid IN ({$conditions['tids']}) ";
        $where_str .= " ORDER BY {$sortBy} ";
        $where_str .= " LIMIT $from, $count ";
        
        $sql = "SELECT p.* FROM kooltao_product p 
        INNER JOIN kooltao_term_data td ON p.pid = td.pid
        INNER JOIN kooltao_term t ON t.tid = td.tid
        $where_str";
        
        $this->productModel->query($sql);
        $list = array();
        while ($p = $this->productModel->fetch_array()) {
            $p['terms'] = $this->productTermList($p['pid']);
            $p['images'] = $this->productImgList($p['pid']);
            $list[$p['pid']] = $p;
        }
        return $list;
    }

    function productListFull ($conditions = null) {
        //page, count, sort
        $page = $conditions['page']? $conditions['page']: 0;
        $count = $conditions['count']? $conditions['count']: DEFAULT_PRODUCT_COUNT;
        $from = $conditions['from']? $conditions['from']: $page*$count;
        $sortBy = $conditions['sort'] ? $conditions['sort'] : '`pid` DESC';
        $where = $conditions['where'];
        
        $list = array();
        $products = $this->productModel->getList('*', $where, $from, $count, $sortBy);
        foreach ($products as $p) {
            $p['terms'] = $this->productTermList($p['pid']);
            $p['images'] = $this->productImgList($p['pid']);
            $list[$p['pid']] = $p;
        }
        return $list;
    }

    function productListJson ($conditions = null) {
        $products = $this->productListFull($conditions);
        $countThis = count($products);
        $countAll = $this->productModel->count();
        $json_arr = array(
            
            'sEcho' => intval($_GET['sEcho']), 
            'iTotalRecords' => $countThis, 
            "iTotalDisplayRecords" => $countAll
        );
        $aaData = array();
        foreach ($products as $p) {
            $subtitle = chinese_substr($p['title'], 0, 25);
            $subtitle = $subtitle == $p['title'] ? $subtitle : $subtitle . '..';
            $source = $p['terms'][TERM_MACHINE_NAME_SOURCE]['tname'];
            $ptype_first = $p['terms'][TERM_MACHINE_NAME_PTYPE_FIRST]['tname'];
            $ptype_second = $p['terms'][TERM_MACHINE_NAME_PTYPE_SECOND]['tname'];
            $color = $p['terms'][TERM_MACHINE_NAME_COLOR]['tname'];
            $aaData[] = array(
                
                $p['pid'], 
                "<a href=\"{$p['url']}\" target=\"_blank\" title=\"{$p['title']}\">" .
                 $subtitle . '</a>', 
                $p['images']['thumbnail'] ? '有' : '-', 
                $p['images']['image'] ? '有' : '-', 
                $p['nick'], 
                $p['sales'], 
                $p['price'], 
                $p['discount'] . '%', 
                
                $source.' '.$p['source_id'], 
                $ptype_first . '/' . $ptype_second, 
                $color, 
                
                $p['fav'], 
                $this->productStatusName($p['status']), 
                $p['username'], 
                date('Y-m-d H:i:s', $p['created']), 
                "<a href='javascript:void(0)' onclick='edit_product({$p['pid']})'>编辑</a>	 |
				<a href='javascript:void(0)' onclick='del_product({$p['pid']})'>删除</a>"
            );
        }
        $json_arr['aaData'] = $aaData;
        return json_encode($json_arr);
    }

    function productStatusName ($status) {
        $statusNames = array(
            
            PRODUCT_STATUS_ADD => '已添加', 
            PRODUCT_STATUS_PUBLISH => '已发布', 
            PRODUCT_STATUS_DELETE => '删除'
        );
        return $statusNames[$status];
    }

    function productAdd ($data) {
        $data['source_id'] = intval($data['source_id']);
        $data['title'] = trim($data['title']);
        $data['description'] = trim($data['description']);
        $data['nick'] = trim($data['nick']);
        $data['sales'] = intval($data['sales']);
        $data['url'] = trim($data['url']);
        $data['shop_url'] = trim($data['shop_url']);
        $data['price'] = floatval($data['price']);
        $data['discount'] = floatval($data['discount']);
        $data['status'] = PRODUCT_STATUS_ADD;
        $data['uid'] = intval($_SESSION['uid']);
        $data['username'] = $_SESSION['username'];
        $data['created'] = $data['changed'] = time();
        unset($data['pid']);
        return $this->productModel->insert($data);
    }

    function productDel ($pid) {
        $this->term_dataModel->delete('pid = ' . $pid);
        $this->imageModel->delete('pid = ' . $pid);
        return $this->productModel->deleteById($pid);
    }

    function productUpdate ($data) {
        $data['pid'] = intval($data['pid']);
        $data['source_id'] && $data['source_id'] = intval($data['source_id']);
        $data['title'] && $data['title'] = trim($data['title']);
        $data['description'] && $data['description'] = trim($data['description']);
        $data['thumbnail'] && $data['thumbnail'] = trim($data['thumbnail']);
        $data['image'] && $data['image'] = trim($data['image']);
        $data['nick'] && $data['nick'] = trim($data['nick']);
        $data['sales'] && $data['sales'] = intval($data['sales']);
        $data['url']&&$data['url'] = trim($data['url']);
        $data['shop_url']&&$data['shop_url'] = trim($data['shop_url']);
        $data['price']&&$data['price'] = floatval($data['price']);
        $data['discount']&&$data['discount'] = floatval($data['discount']);
        $data['changed'] = time();
        return $this->productModel->update($data);
    }

    function get_data_remote ($source, $source_id) {
        $source = $this->termModel->getOneById($source);
        $data = array();
        if ($source['name'] == '淘宝') {
            require_once ROOT . '/includes/TOP_Module/TaoBaoSDK_Interface.php';
            $req = new TaobaokeItemsDetailGetRequest();
            $req->setFields(
            "num_iid,title,nick,pic_url,price,click_url,commission,commission_rate,commission_num,
					commission_volume,shop_click_url,seller_credit_score,item_location,volume,
					type,cid,item_img,prop_img"); //需返回的字段列表  pic_url
            $req->setNumIids($source_id); //淘宝客商品数字id串.最大输入10个.格式如:"value1,value2,value3" 用" , "号分隔商品id.
            $req->setPid(TAOBAOKE_PID);
            $resp = $c->execute($req); //查询完成
            

            $data['title'] = (string) $resp->taobaoke_item_details->taobaoke_item_detail->item->title;
            $data['url'] = (string) $resp->taobaoke_item_details->taobaoke_item_detail->click_url;
            $data['shop_url'] = (string) $resp->taobaoke_item_details->taobaoke_item_detail->shop_click_url;
            $data['nick'] = (string) $resp->taobaoke_item_details->taobaoke_item_detail->item->nick;
            $data['price'] = (string) $resp->taobaoke_item_details->taobaoke_item_detail->item->price;
        }
        
        return $data;
    }
    //search 结果数据
    function productListSearch ($word,$conditions = null) {
        //$sql = "SELECT p.* FROM kooltao_product p WHERE p.description LIKE '%{$word}%' order by p.pid DESC";
        //$this->productModel->query($sql);
        $page = $conditions['page']? $conditions['page']: 0;
        $count = $conditions['count']? $conditions['count']: DEFAULT_PRODUCT_COUNT;
        $from = $conditions['from']? $conditions['from']: $page*$count;
        $sortBy = $conditions['sort'] ? $conditions['sort'] : '`pid` DESC';
        $where = "description LIKE '%{$word}%'";

        $list = array();
        $products = $this->productModel->getList('*', $where, $from, $count, $sortBy);
        foreach ($products as $p) {
            $p['terms'] = $this->productTermList($p['pid']);
            $p['images'] = $this->productImgList($p['pid']);
            $list[$p['pid']] = $p;
        }
        return $list;
    }
    
    function productGetOneSample($pid){
        return $this->productModel->getOneById($pid);
    }
    
    function addFav($pid, $uid){
        $product = $this->productGetOneSample($pid);
        if(!$product){
            return -1;
        }
        $user = $this->userModel->getOneById($uid);
        if(!$user){
            return -2;
        }
        if($uid != $_SESSION['uid']){
            return -3;
        }
        
        $data = array('uid' => $uid, 'pid' => $pid);
        $this->favoriteModel->insert($data);
        $product['fav']++;
        $this->productUpdate($product);
        return $product['fav'];
    }
}